package com.jd.dlc.limit.scan;

import com.jd.dlc.annotation.DlcLimiter;
import com.jd.dlc.spring.SpringUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.*;

/**
 * @description:
 * @author: wshang
 * @date: 2022年06月12 15:13
 */
@Component
public class ScanSupport {

    /**
     * 扫描包
     *
     * @return
     */
    public Set<Class> doScanClass() {

        Set<Class> classSet = new HashSet<>();
        Map<String, Object> handelerBeans = SpringUtils.getBeansWithAnnotation(Service.class);
        if (handelerBeans == null) {
            return null;
        }
        Map<String, Object> ct = SpringUtils.getBeansWithAnnotation(Controller.class);
        if (ct != null) {
            handelerBeans.putAll(ct);
        }
        Map<String, Object> co = SpringUtils.getBeansWithAnnotation(Component.class);
        if (co != null) {
            handelerBeans.putAll(co);
        }

        for (Object obj : handelerBeans.values()) {
            Method[] methods = obj.getClass().getDeclaredMethods();
            out:
            for (Method method : methods) {
                if (AnnotationUtils.findAnnotation(method, DlcLimiter.class) != null) {
                    classSet.add(obj.getClass());
                    break out;
                }
            }
        }
        return classSet;
    }

}
